/*
*
*/
#include <stdarg.h>
#include "LPC2210.h"


void uartInit(unsigned int auxClk)
{
	unsigned int div;

    PINSEL0 = (PINSEL0 & ~0xF) | 5;
    
	IO2DIR |= 0x01000000;
	IO2CLR = 0x01000000;
	
	U0LCR = 0x83;
	div = (auxClk / 16) / 57600;
	U0DLM = (unsigned char)((div >> 8) & 0xff);
	U0DLL = (unsigned char)(div & 0xff);
	U0LCR = 0x03;
}

int uartSendByte(unsigned char ch)
{
	if(U0LSR & 0x40){
		U0THR = ch;
		return 0;
	}

	return -1;
}


int uartRecvByte(unsigned char *ch)
{
	if(U0LSR & 0x01){
		*ch = U0RBR;
		return 0;
	}

	return -1;
}

void uartPrintStr(char *str)
{
    int i = 0;
    
    while(str[i]){
        while(uartSendByte(str[i]));
        i++;
    }
}

void uartPrintHex(unsigned int x)
{
    int i;
    
    uartPrintStr("0x");
    for(i = 0; i < 32; i += 4){
        char buf[2];
        char a = 0xF &(x >> (28 - i));
        if(a < 10){
            buf[0] = '0' + a;
        }else{
            buf[0] = 'A' + a - 10;
        }
        buf[1] = 0;
        uartPrintStr(buf);
    }
}

void uartPrintNL(void)
{
    uartPrintStr("\r\n");
}

int uartPrintf(const char *fmt, ...)
{
#define UART_PRINTF_BUF_SIZE    256

  va_list   va;
  int ret;
  static char uartPrintfBuf[UART_PRINTF_BUF_SIZE];

  va_start(va, fmt);
  ret = vsnprintf(uartPrintfBuf, UART_PRINTF_BUF_SIZE, fmt, va);
  va_end(va);

  uartPrintStr(uartPrintfBuf);

  return ret;
#undef UART_PRINTF_BUF_SIZE
}

